package com.suep.business.controller;

import com.suep.business.domain.UserAddress;
import com.suep.business.service.IUserAddressService;
import com.suep.system.config.BaseR;
import com.suep.system.utils.RequestAttributeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/userAddress")
public class UserAddressController {

    @Autowired
    private IUserAddressService userAddressService;

    @GetMapping("/getById")
    public BaseR<UserAddress> getById(@RequestParam Integer addressId) {
        return new BaseR<>().ok("查询成功", userAddressService.selectUserAddressById(addressId));
    }

    @GetMapping("/getByUserId")
    public BaseR<List<UserAddress>> getByUserId(HttpServletRequest request) {
        Integer userId = Integer.parseInt(request.getAttribute("userId").toString());
        return new BaseR<>().ok("查询成功", userAddressService.selectUserAddressByUserId(userId));
    }

    @PostMapping("/add")
    public BaseR<Integer> add(@RequestBody UserAddress userAddress,HttpServletRequest request) {
        Integer userId= RequestAttributeUtil.getUserIdFromRequest(request);
        userAddress.setUserId(userId);
        return new BaseR<>().ok("插入成功", userAddressService.insertUserAddress(userAddress));
    }

    @PutMapping("/change")
    public BaseR<Integer> change(@RequestBody UserAddress userAddress) {
        return new BaseR<>().ok("更新成功", userAddressService.updateUserAddress(userAddress));
    }

    @DeleteMapping("/remove")
    public BaseR<Integer> remove(@RequestParam Integer addressId) {
        return new BaseR<>().ok("删除成功", userAddressService.deleteUserAddressById(addressId));
    }
}